import os
import json
import base64
import re


# 明确写入的资源类型
jsonExt = ["json", "lh", "ls", "lmat", "atlas",
           "mcc", "rendertexture", "controller"]
binExt = ["lm", "lani", "bin", "mc", "skel"]
mediaExt = ["mp3", "wav", "ogg", "mp4", "png", "jpg", "jpeg"]
txtExt = ["shader", "txt"]


def getExt(str):
    list = str.split(".")
    ext = list[len(list) - 1]
    return ext


def isJson(file):
    ext = getExt(file)
    for item in jsonExt:
        if ext == item:
            return True
    return False


def isBin(file):
    ext = getExt(file)
    for item in binExt:
        if ext == item:
            return True
    return False


def isMedia(file):
    ext = getExt(file)
    for item in mediaExt:
        if ext == item:
            return True
    return False

def isTxt(file):
    ext = getExt(file)
    for item in txtExt:
        if ext == item:
            return True
    return False


# 将所有资源组织成键值对 {“相对路径文件名”：“json|base64”}
dataJson = {}
curPath = os.getcwd()
assetsPath = curPath + "\\release\\web"
for root, dirs, files in os.walk(assetsPath):
    for file in files:
        fullPath = root + "\\" + file
        relativePath = fullPath.replace(assetsPath + "\\", "")
        relativePath = relativePath.replace('\\', "/")
        fullPath = fullPath.replace('\\', "/")
        if isJson(file):
            with open(fullPath, encoding="utf-8") as f:
                b = f.read()
                try:
                    b = json.loads(b)
                    dataJson[str(relativePath)] = b
                # atlas也可能是spine动画资源后缀，当文本处理
                except:
                    print("not json maybe txt")
                    b = re.sub(r'\n\s+', r'\n', b)
                    dataJson[str(relativePath)] = b

        elif isMedia(file) or isBin(file):
            with open(fullPath, "rb") as f:
                b = f.read()
                b64Str = str(base64.b64encode(b))
                searchObj = re.search(r'\'.*\'', b64Str)
                b64StrF = searchObj.group().replace("\'", "")
                dataJson[str(relativePath)] = b64StrF
        elif isTxt(file):
            with open(fullPath, encoding="utf-8") as f:
                b = f.read()
                b = re.sub(r'\n\s+', r'\n', b)
                dataJson[str(relativePath)] = b
        # print(fullPath, relativePath)


def readFileStr(file):
    with open(file, "r", encoding="utf-8") as f:
        str = f.read()
        return str


def addScriptTag(text):
    return "\n<script type=\"text/javascript\">\n" + text + "\n</script>\n"


def joinJsScriptStr(path):
    jsStr = ""
    for root, dirs, files in os.walk(path):
        for file in files:
            fullPath = root + "/" + file
            jsStr += addScriptTag(readFileStr(fullPath))
    return jsStr


dataStr = "assetsPackage=" + json.dumps(dataJson)
with open("data.js", "w", encoding="utf-8") as f:
    f.write(dataStr)


scriptKey = "{#scripts}"
libsPath = curPath + "/release/web/libs/min"
jsPath = curPath + "/release/web/js"


# 先写入js库,然后dataStr,FakeHttp.js,最后是引擎打包后的代码
jsScriptStr = ""
jsScriptStr += joinJsScriptStr(libsPath)
jsScriptStr += addScriptTag(dataStr)
jsScriptStr += addScriptTag(readFileStr(curPath + "/FakeHttp.js"))
jsScriptStr += joinJsScriptStr(jsPath)


# 找到所有的index-xx.html文件，据scriptKey替换写入jsScriptStr
def searchHtml(path):
    for x in os.listdir(path):
        file = os.path.join(path, x)
        if os.path.isfile(file):
            if x.find("index-") != -1 and getExt(x) == "html":
                htmlPath = curPath + "/" + x
                toHtmlPath = curPath + "/release/web/" + x
                with open(toHtmlPath, "w", encoding="utf-8") as f:
                    htmlStr = readFileStr(htmlPath).replace(
                        scriptKey, jsScriptStr)
                    f.write(htmlStr)


searchHtml("./")
